<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class ClearCacheController extends BaseController
{

    /*
     * 清除缓存接口
     */
    public function index(Request $request)
    {
        $key = $request->input('redis_key');
        // 清除二级栏目下的缓存
        if ($key == 'template:area:5:*') {
            $data   = Redis::Keys($key);
            $result = Redis::pipeline(function ($pipe) use ($data) {
                foreach ($data as $dateKey => $value) {
                    $pipe->del($value);
                }
            });
            return count($result);
        }

        // 清除全部媒资的缓存
        if ($key == 'vasseti:*') {
            $data   = Redis::Keys($key);
            $result = Redis::pipeline(function ($pipe) use ($data) {
                foreach ($data as $dateKey => $value) {
                    $pipe->del($value);
                }
            });
            return count($result);
        }

        return Redis::command('Del', [$key]);
    }

    /**
     * 测试redis 是否能够连接
     */
    public function show(Request $request)
    {
        $redisConfig = $request->input('redis_config');

        // 检查环境配置
        $phpConfig = $request->input('php_config');
        if ($phpConfig) {
            if (extension_loaded('mysql')) {
                $result1 = 'mysql existed';
            } else {
                $result1 = 'mysql not existed';
            }

            if (extension_loaded('PDO')) {
                $result2 = 'pdo existed';
            } else {
                $result2 = 'pdo not existed';
            }

            if (extension_loaded('redis')) {
                $result3 = 'redis existed';
            } else {
                $result3 = 'redis not existed';
            }

            if (extension_loaded('pdo_mysql')) {
                $result4 = 'pdo_mysql existed';
            } else {
                $result4 = 'pdo_mysql not existed';
            }
            if (extension_loaded('curl')) {
                $result5 = 'curl existed';
            } else {
                $result5 = 'curl not existed';
            }
            $result = [
                $result1, $result2, $result3, $result4, $result5,
            ];
            return response()->json(['status' => '200', 'data' => ['takename' => $result]]);
        }

        if ($redisConfig) {
            $redis = Redis::connection();
            dd($redis);
        }
        $redis = Redis::connection();
        $redis->set('takename', '1234');
        $result = $redis->get('takename');
        return response()->json(['status' => '200', 'data' => ['takename' => $result]]);
    }
}
